package com.ithuang.quartz.utils;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.imageio.ImageIO;

import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.entity.UrlEncodedFormEntity;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.http.message.BasicNameValuePair;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;

public class ImageUtil {

    // 1将彩色图像转换为灰度图像，可以减少噪声和提高OCR的准确性。使用Java的BufferedImage类可以轻松实现这一点。
    public static BufferedImage convertToGrayscale(BufferedImage image) {
        BufferedImage grayscaleImage = new BufferedImage(image.getWidth(), image.getHeight(),
                BufferedImage.TYPE_BYTE_GRAY);
        Graphics2D g = grayscaleImage.createGraphics();
        g.drawImage(image, 0, 0, null);
        g.dispose();
        return grayscaleImage;
    }

    // 2二值化是将图像转换为黑白图像。通过二值化，可以去除背景噪声，突出目标区域。
    public static BufferedImage binarizeImage(BufferedImage image) {
        BufferedImage binaryImage = new BufferedImage(image.getWidth(), image.getHeight(),
                BufferedImage.TYPE_BYTE_BINARY);
        Graphics2D g = binaryImage.createGraphics();
        g.drawImage(image, 0, 0, null);
        g.dispose();
        return binaryImage;
    }

    // 3去噪是通过算法去除图像中的噪声点，进一步提高OCR的准确性。常用的去噪算法包括中值滤波、均值滤波等。
    public BufferedImage removeNoise(BufferedImage image) {
        // 使用OpenCV库进行去噪
        // 这里假设已经引入了OpenCV库
        // Mat src = Imgcodecs.imread(imagePath);
        // Mat dest = new Mat();
        // Imgproc.medianBlur(src, dest, 3);
        // 转换回BufferedImage
        // return matToBufferedImage(null);
        return null;
    }

    // 1. 使用正则表达式提取数字
    public static String extractNumbers(String text) {
        String res = "";
        Matcher matcher = Pattern.compile("\\d+").matcher(text);
        while (matcher.find()) {
            res+=matcher.group();
        }
        return res;
    }

    public static String get(String url) throws org.apache.hc.core5.http.ParseException {
        String resultContent = null;
        HttpGet httpGet = new HttpGet(url);
        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
            try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
                // 获取状态码
                System.out.println(response.getVersion()); // HTTP/1.1
                System.out.println(response.getCode()); // 200
                System.out.println(response.getReasonPhrase()); // OK
                HttpEntity entity = response.getEntity();
                // 获取响应信息
                resultContent = EntityUtils.toString(entity);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return resultContent;
    }

    public static String post(String url) throws org.apache.hc.core5.http.ParseException {
        String result = null;
        HttpPost httpPost = new HttpPost(url);
        // 表单参数
        List<BasicNameValuePair> nvps = new ArrayList<>();
        // POST 请求参数
        nvps.add(new BasicNameValuePair("username", "wdbyte.com"));
        nvps.add(new BasicNameValuePair("password", "secret"));
        httpPost.setEntity(new UrlEncodedFormEntity(nvps));
        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
            try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
                System.out.println(response.getVersion()); // HTTP/1.1
                System.out.println(response.getCode()); // 200
                System.out.println(response.getReasonPhrase()); // OK

                HttpEntity entity = response.getEntity();
                // 获取响应信息
                result = EntityUtils.toString(entity);
                // 确保流被完全消费
                EntityUtils.consume(entity);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static String token() {
        // 创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            // 创建HttpPost对象
            HttpPost httpPost = new HttpPost("https://aip.baidubce.com/oauth/2.0/token");
            List<BasicNameValuePair> nvps = new ArrayList<>();
            nvps.add(new BasicNameValuePair("grant_type", "client_credentials"));
            nvps.add(new BasicNameValuePair("client_id", "4ww9aCyZqNGuiXI9EK5oDpHv"));
            nvps.add(new BasicNameValuePair("client_secret", "0QgND8pQo4tQcvqpNk5ZtIVNcIqWceYm"));
            httpPost.setEntity(new UrlEncodedFormEntity(nvps));
            httpPost.setHeader("Content-type", "application/json");
            httpPost.setHeader("Accept", "application/json");

            // 执行请求
            CloseableHttpResponse response = httpClient.execute(httpPost);

            try {
                // 获取响应实体
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    // 转换响应内容为字符串
                    String result = EntityUtils.toString(entity);
                    JSONObject jsonObject = JSONObject.parseObject(result);
                    String access_token = (String) jsonObject.get("access_token");

                    return access_token;
                }
                return null;
            } finally {
                response.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public static String convertImageToBase64Str(File f) {
        ByteArrayOutputStream baos = null;
        try {
            baos = new ByteArrayOutputStream();
            BufferedImage bufferedImage = ImageIO.read(f);
            bufferedImage = convertToGrayscale(bufferedImage);
            bufferedImage = binarizeImage(bufferedImage);
            ImageIO.write(bufferedImage, "bmp", baos);
            byte[] bytes = baos.toByteArray();
            return Base64.getEncoder().encodeToString(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (baos != null) {
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public static String convertImageToBase64Str(BufferedImage bufferedImage) {
        ByteArrayOutputStream baos = null;
        try {
            baos = new ByteArrayOutputStream();
            bufferedImage = convertToGrayscale(bufferedImage);
            bufferedImage = binarizeImage(bufferedImage);
            ImageIO.write(bufferedImage, "png", baos);
            byte[] bytes = baos.toByteArray();
            return Base64.getEncoder().encodeToString(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (baos != null) {
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public static String shibieshuzi(String img64) {
        String t = token();
        // 创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            // 创建HttpPost对象
            // HttpPost httpPost = new HttpPost("https://aip.baidubce.com/rest/2.0/ocr/v1/numbers?access_token=" + t);
            // HttpPost httpPost = new HttpPost("https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic?access_token=" + t);
            HttpPost httpPost = new HttpPost("https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic?access_token=" + t);
            
            
            List<BasicNameValuePair> nvps = new ArrayList<>();
            nvps.add(new BasicNameValuePair("image", img64));
            httpPost.setEntity(new UrlEncodedFormEntity(nvps));

            httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
            httpPost.setHeader("Accept", "application/json");

            // 执行请求
            CloseableHttpResponse response = httpClient.execute(httpPost);

            try {
                // 获取响应实体
                HttpEntity entity = response.getEntity();
                if (entity != null) {


                    // 转换响应内容为字符串
                    String result = EntityUtils.toString(entity);
                    // return result;


                    JSONObject jsonObject = JSONObject.parseObject(result);
                    JSONArray arr = jsonObject.getJSONArray("words_result");
                    JSONArray a2 = new JSONArray();
                    JSONObject o1 = (JSONObject) arr.get(0);
                    JSONObject o2 = (JSONObject) arr.get(1);
                    JSONObject o3 = (JSONObject) arr.get(2);
                    // JSONObject o4 = (JSONObject) arr.get(3);
                    String s = new String();
                    s+=o1.getString("words");
                    s+=o2.getString("words");
                    s+=o3.getString("words");
                    // s+=o4.getString("words");

                    s = s.replaceFirst("诚成木业工厂", "");
                    s = s.replaceFirst("前", "");
                    s = s.replaceFirst("后", "");
                    s = s.replaceFirst("左", "");
                    s = s.replaceFirst("右", "");
                    // a2.add(arr.get(0));
                    // a2.add(arr.get(1));
                    // a2.add(arr.get(2));
                    // a2.add(arr.get(3));
                    // JSONObject o =  arr.getJSONObject(0);
                    // String res = o.getString("words");
                    // return a2.toJSONString();
                    return s;
                }
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            } finally {
                response.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}